package com.cloudkinto.service.app.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.entity.AppUpdateDo;
import com.cloudkinto.dao.AppUpdateDao;
import com.cloudkinto.service.app.AppUpdateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.app.vo.AppUpdateNewestRes;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  service实现类
 * </p>
 * @author long
 * @since 2025-08-13
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AppUpdateServiceImpl extends ServiceImpl<AppUpdateDao, AppUpdateDo> implements AppUpdateService {
    @Value("${gbc.customer}")
    private String customer;

    //获取最新版本
    @Override
    public AppUpdateNewestRes getTwoAppNewestVersion() {
        AppUpdateDo appUpdateDo = baseMapper.selectOne(new LambdaQueryWrapper<AppUpdateDo>().last(" order by id desc limit 1"));
        if (appUpdateDo == null) {
            return null;
        }
        String url = "https://image.cloudkinto.com/app/company_two/" + appUpdateDo.getVersionCode();

//        String url = "";
//        if ("kk".equals(customer)) {
//            url = "https://wms-kk.cangceo.com/api/admin/app/AppUpdate";
//        } else {
//            url = "https://wms-la.cangceo.com/api/admin/app/AppUpdate";
//        }
//        url = "http://192.168.1.32:8086/api/admin/app/AppUpdate";
//        url += "/downTwoAppNewest";
        return new AppUpdateNewestRes(appUpdateDo.getId(), appUpdateDo.getVersion(), appUpdateDo.getVersionName(),
                appUpdateDo.getContent(), appUpdateDo.getVersionCode(), url);
    }


    @Override
    public void downTwoAppNewest(HttpServletResponse response) {

        // 查询最新的App更新信息
        AppUpdateDo appUpdateDo = baseMapper.selectOne(
                new LambdaQueryWrapper<AppUpdateDo>().last("order by id desc limit 1")
        );
        if (appUpdateDo == null) {
            return;
        }

        // 网络文件URL
        String fileUrl = "https://image.cloudkinto.com/app/company_two/" + appUpdateDo.getVersionCode();
        // OSS允许的Referer地址（根据实际OSS配置修改）
        String referer = "https://你的域名.com"; // 例如：https://www.example.com

        HttpURLConnection connection = null;
        InputStream in = null;
        OutputStream out = null;

        try {
            // 1. 打开网络连接
            URL url = new URL(fileUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 添加Referer请求头（关键修改）
            connection.setRequestProperty("Referer", "https://wms-la.cangceo.com");

            connection.setConnectTimeout(5000); // 5秒连接超时
            connection.setReadTimeout(10000);   // 10秒读取超时

            // 检查连接状态（200表示成功）
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                // 对于403错误，可能是Referer不匹配导致的
                if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                    throw new BizException("文件下载被拒绝，请检查Referer配置");
                }
                throw new BizException("文件下载失败，服务器返回状态：" + responseCode);
            }

            // 2. 设置响应头
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            String contentType = connection.getContentType();
            response.setHeader("Content-Type", contentType != null ? contentType : "application/octet-stream");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            String fileName = URLEncoder.encode(appUpdateDo.getVersionName(), StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 3. 缓冲流读写（避免内存溢出）
            in = new BufferedInputStream(connection.getInputStream());
            out = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[4096]; // 4KB缓冲区
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();

        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            // 4. 关闭资源
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }









    public void downTwoAppNewest1(HttpServletResponse response) {
        AppUpdateDo appUpdateDo = baseMapper.selectOne(new LambdaQueryWrapper<AppUpdateDo>().last(" order by id desc limit 1"));
        if (appUpdateDo == null) {
            return;
        }
        String url = "https://image.cloudkinto.com/app/company_two/" + appUpdateDo.getVersionCode();
        File tempFile = new File(url);
        if (!tempFile.exists()) {
            throw new BizException("文件不存在,下载失败");
        }

        try {
            response.setCharacterEncoding("UTF-8");
            String type = new MimetypesFileTypeMap().getContentType(tempFile);

            response.setHeader("content-Type", type);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(appUpdateDo.getVersionName(), "UTF-8"));
            response.getOutputStream().write(Files.readAllBytes(tempFile.toPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}